﻿<?LassoScript

	/*

		lp8-5-5/b.lasso

		The MIT License

		Copyright (c) 2009, Douglas Burchard.
		
		Permission is hereby granted, free of charge, to any person obtaining a copy
		of this software and associated documentation files (the "Software"), to deal
		in the Software without restriction, including without limitation the rights
		to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
		copies of the Software, and to permit persons to whom the Software is
		furnished to do so, subject to the following conditions:

		The above copyright notice and this permission notice shall be included in
		all copies or substantial portions of the Software.

		THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
		IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
		FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
		AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
		LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
		OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
		THE SOFTWARE.

	*/


	// =====================================================================
	/*
		B_Template
		--------------------------------------------------------------------

			===========================================
			| B_Template
			|
			===========================================
			| Parameters
			-------------------------------------------
			| template_location : String
			| base : String
			| current_instance : String
			| mime_type : String
			|
			===========================================
			| Tags
			-------------------------------------------
			| onCreate(location: String[, type : String][, find : String|RegExp = replace : String|RegExp]) : Null
			| onCreate() : Null
			| Location(location : String) : Null
			| Location() : String
			| MimeType(type : String) : Null
			| MimeType() : String
			| Base(base : String) : Null
			| Base() : String
			| CurrentInstance(package : String) : Null
			| CurrentInstance() : String
			| Apply(find : String|RegExp = replace : String|RegExp[, find : String|RegExp = replace : String|RegExp]) : Null
			| ApplyToBase(find : String|RegExp = replace : String|RegExp[, find : String|RegExp = replace : String|RegExp]) : Null
			| Extract(find : String|RegExp) : B_Template
			| ServeNow() : Null
			| ServeAtEnd() : Null
			|

		This custom prototype reads in the specified template, and for each 
		name/value parameter, replaces all instances of the "name" portion 
		with the associated "value" portion.

		Optionally allows a specified MIME type, which defaults to "text/html" if
		not specified.

		This prototype can be used like a tag in a single call, to apply 
		and serve a template immediately -- aborting the remainder of the code.

			B_Template('location',
				-Type='text/html',
				'find'='replace',
				'find'='replace');

		Or, the protype can be used more programatically.

			Local('mytemplate' = B_Template);
			#mytemplate -> Location('location');
			#mytemplate -> MimeType('text/html');
			#mytemplate -> Apply('find'='replace', 'find'='replace');
			#mytemplate -> ServeNow;

		All substitutions are applied consecutively. For more complex
		applications, substitutions can be split across separate calls.

			Local('mytemplate' = B_Template);
			#mytemplate -> Location('location');
			#mytemplate -> MimeType('text/html');
			#mytemplate -> Apply('find'='replace');
			#mytemplate -> Apply('find'='replace');
			#mytemplate -> Apply('find'='replace');
			#mytemplate -> ServeAtEnd;

		Portions of templates can also be extracted, used as templates in
		their own right, then inserted back into the original.

			Local('mytemplate' = B_Template);
			#mytemplate -> Location('location');
			#mytemplate -> MimeType('text/html');

			Local('myinsertion' = String);
			Local('mysubtemplate' = (#mytemplate -> Extract('find')));
			Records;
				#mysubtemplate -> ApplyToBase('find'=Field('replace'));
				#myinsertion += (#mysubtemplate -> CurrentInstance);
			/Records;

			#mytemplate -> Apply((#mysubtemplate -> Base)=#myinsertion);
			#mytemplate -> ServeAtEnd;

	*/
	// ---------------------------------------------------------------------
		Define_Type('Template',
				-NameSpace='B_',
				-Description='This custom prototype reads in the specified template, and for each 
name/value parameter, replaces all instances of the "name" portion 
with the associated "value" portion.

Optionally allows a specified MIME type, which defaults to "text/html" if
not specified.

This prototype can be used like a tag in a single call, to apply 
and serve a template immediately -- aborting the remainder of the code.

	B_Template(\'location\',
		-Type=\'text/html\',
		\'find\'=\'replace\',
		\'find\'=\'replace\');

Or, the protype can be used more programatically.

	Local(\'mytemplate\' = B_Template);
	#mytemplate -> Location(\'location\');
	#mytemplate -> MimeType(\'text/html\');
	#mytemplate -> Apply(\'find\'=\'replace\', \'find\'=\'replace\');
	#mytemplate -> ServeNow;

For more complex applications, substitutions can be applied consecutively.

	Local(\'mytemplate\' = B_Template);
	#mytemplate -> Location(\'location\');
	#mytemplate -> MimeType(\'text/html\');
	#mytemplate -> Apply(\'find\'=\'replace\', \'find\'=\'replace\');
	#mytemplate -> Apply(\'find\'=\'replace\', \'find\'=\'replace\');
	#mytemplate -> Apply(\'find\'=\'replace\', \'find\'=\'replace\');
	#mytemplate -> ServeAtEnd;

Portions of templates can also be extracted, used as templates in
their own right, then inserted back into the original.

	Local(\'mytemplate\' = B_Template);
	#mytemplate -> Location(\'location\');
	#mytemplate -> MimeType(\'text/html\');

	Local(\'myinsertion\' = String);
	Local(\'mysubtemplate\' = (#mytemplate -> Extract(\'find\')));
	Records;
		#mysubtemplate -> ApplyToBase(\'find\'=Field(\'replace\'));
		#myinsertion+= (#mysubtemplate -> CurrentInstance);
	/Records;

	#mytemplate -> Apply((#mysubtemplate -> Default)=#myinsertion);
	#mytemplate -> ServeAtEnd;',
				-EncodeNone);

			Local('template_location');
			Local('mime_type');
			Local('base');
			Local('current_instance');

			Define_Tag('onCreate', -Optional='location', -Optional='type', -EncodeNone);
				(Self -> 'template_location') = String(Local('location'));
				(Self -> 'mime_type') = String(Local('type'));
				(Self -> 'base') = String;
				(Self -> 'current_instance') = String;
				If(String(Local('location')) -> Size);
					Iterate(Params, Local('p'));
						If((#p -> Type) == (Pair -> Type));
							If((#p -> Name) != '-Type' && (#p -> Name) != '-Location');
								Self -> Apply((#p -> Name)=(#p -> Value));
							/If;
						/If;
					/Iterate;
					Self -> ServeNow;
				/If;
			/Define_Tag;

			Define_Tag('Location', -Optional='location', -EncodeNone);
				If((Local('location') -> Type) != (Null -> Type));
					(Self -> 'template_location') = String(Local('location'));
					Local('bytestream' = Include_Raw(Self -> 'template_location'));

					#bytestream -> RemoveLeading(BOM_UTF32BE);
					#bytestream -> RemoveLeading(BOM_UTF32LE);
					#bytestream -> RemoveLeading(BOM_UTF16BE);
					#bytestream -> RemoveLeading(BOM_UTF16LE);
					#bytestream -> RemoveLeading(BOM_UTF8);

					Self -> Base(String(#bytestream));
					Self -> CurrentInstance(Self -> Base);
				Else;
					Return(Self -> 'template_location');
				/If;
			/Define_Tag;

			Define_Tag('MimeType', -Optional='type', -EncodeNone);
				If((Local('type') -> Type) != (Null -> Type));
					(Self -> 'mime_type') = String(Local('type'));
				Else(!((Self -> 'mime_type') -> Size));
					Return('text/html');
				Else;
					Return(Self -> 'mime_type');
				/If;
			/Define_Tag;

			Define_Tag('Base', -Optional='base', -EncodeNone);
				If((Local('base') -> Type) != (Null -> Type));
					(Self -> 'base') = Local('base');
				Else;
					Return(Self -> 'base');
				/If;
			/Define_Tag;

			Define_Tag('CurrentInstance', -Optional='package', -EncodeNone);
				If((Local('package') -> Type) != (Null -> Type));
					(Self -> 'current_instance') = String(Local('package'));
				Else;
					Return(Self -> 'current_instance');
				/If;
			/Define_Tag;

			Define_Tag('Apply');
				Iterate(Params, Local('p'));
					If((#p -> Type) == (Pair -> Type));
						Self -> CurrentInstance(String_Replace((Self -> CurrentInstance), -Find=(#p -> Name), -Replace=(#p -> Value)));
					Else((#p -> Type) == 'RegExp');
						#p -> Input(Self -> CurrentInstance);
						Self -> CurrentInstance(#p -> ReplaceAll);
					/If;
				/Iterate;
			/Define_Tag;

			Define_Tag('ApplyToBase');
				Self -> CurrentInstance(Self -> Base);
				Iterate(Params, Local('p'));
					If((#p -> Type) == (Pair -> Type));
						Self -> CurrentInstance(String_Replace((Self -> CurrentInstance), -Find=(#p -> Name), -Replace=(#p -> Value)));
					Else((#p -> Type) == 'RegExp');
						#p -> Input(Self -> CurrentInstance);
						Self -> CurrentInstance(#p -> ReplaceAll);
					/If;
				/Iterate;
			/Define_Tag;

			Define_Tag('Extract', -Optional='find', -EncodeNone);
				Local('output' = B_Template);
				If((#find -> Type) == 'RegExp');
					Local('find') -> Input(Self -> CurrentInstance);
					If(#find -> Find);
						#output -> Base(#find -> MatchString);
						#output -> CurrentInstance(#find -> MatchString);
					/If;
				Else;
					Local('excerpt' = RegExp(-Find=String(Local('find')), -Input=(Self -> CurrentInstance), -IgnoreCase));
					If(#excerpt -> Find);
						#output -> Base(#excerpt -> MatchString);
						#output -> CurrentInstance(#excerpt -> MatchString);
					/If;
				/If;
				Return(#output);
			/Define_Tag;

			Define_Tag('ServeNow');
				File_Serve((Self -> CurrentInstance), -Type=(Self -> MimeType));
			/Define_Tag;

			Define_Tag('ServeAtEnd');
				Define_AtEnd(Self -> ServeNow);
			/Define_Tag;

		/Define_Type;
	// =====================================================================


	// =====================================================================
	/*
		B_UUID
		--------------------------------------------------------------------

			===========================================
			| B_UUID
			|
			===========================================
			| Tags
			-------------------------------------------
			| onCreate()						String
			| ToHex(Integer)					String
			| ToChar(Integer)					String
			| GenerateNumber(Integer,Integer)	Integer
			| GenerateUUID()					String
			|

		This custom prototype returns a version 4 (random) Universally Unique
		Identifier (UUID). For more information on UUIDs, please read the 
		Wikipedia entry, currently at:
		
			http://en.wikipedia.org/wiki/uuid

	*/
	// ---------------------------------------------------------------------
		Define_Type('UUID',
				-NameSpace='B_',
				-Prototype,
				-Description='This custom prototype returns a version 4 (random) ' +
					'Universally Unique Identifier (UUID). For more information ' +
					'on UUIDs, please read the Wikipedia entry, currently at: ' +
					'http://en.wikipedia.org/wiki/uuid');

			Define_Tag('onCreate');
				Return(String(Self -> GenerateUUID));
			/Define_Tag;

			Define_Tag('ToHex', -Required='d', -EncodeNone);
				Local('r' = (#d % (16)));
				Local('result');
				If((#d - #r) == (0));
					#result = (Self -> ToChar(#r));
				Else;
					#result = ((Self -> ToHex((#d - #r) / (16))) + (Self -> ToChar(#r)));
				/If;
				Return(#result);
			/Define_Tag;

			Define_Tag('ToChar', -Required='n', -EncodeNone);
				Local('alpha' = '0123456789abcdef');
				Return(#alpha -> Get(#n + (1)));
			/Define_Tag;

			Define_Tag('GenerateNumber', -Required='l', -Required='u', -EncodeNone);
				Local('n' = Math_Random(-Lower=(Local('l') - (1)), -Upper=Local('u')));
				#n = ((#n < Local('l')) ? Local('u') | (#n));
				Return(#n);
			/Define_Tag;

			Define_Tag('GenerateUUID', -EncodeNone);
				Local('random_bytes' = String);

				#random_bytes += (Self -> ToHex(_date_msec));
				#random_bytes -> Reverse;
				While((#random_bytes -> Size) < (30));
					#random_bytes += (Self -> ToHex(Self -> GenerateNumber((0), (15))));
				/While;
				#random_bytes -> Lowercase;
				#random_bytes = String_Insert(#random_bytes, -Position=(9), -Text='-');
				#random_bytes = String_Insert(#random_bytes, -Position=(14), -Text='-4');
				#random_bytes = String_Insert(#random_bytes, -Position=(19), -Text=('-' + (Array('8','9','a','b') -> Get(Self -> ToHex(Self -> GenerateNumber((1), (4)))))));
				#random_bytes = String_Insert(#random_bytes, -Position=(24), -Text='-');

				Return(#random_bytes);
			/Define_Tag;

		/Define_Type;
	// =====================================================================

?>